import os
import sys

from PyQt6.QtCore import Qt, QTimer
from PyQt6.QtGui import QPalette, QColor, QIcon
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                             QHBoxLayout, QLineEdit, QPushButton, QLabel,
                             QListWidget, QGroupBox, QDialog, QTextEdit,
                             QListWidgetItem, QComboBox)

from api.ApplymailApi import ApplymailApi
from api.GetmailApi import GetmailApi
from api.RootshPage import RootshPage
from api.GetCode import GetCode
from bs4 import BeautifulSoup


class EmailDetailDialog(QDialog):
    """邮件详情对话框"""

    def __init__(self, subject, sender, time, content, parent=None):
        super().__init__(parent)
        self.setWindowTitle("邮件详情")
        self.setMinimumSize(400, 300)

        # 设置样式
        self.setStyleSheet("""
            QDialog {
                background-color: #F5F5F7;
            }
            QLabel {
                font-size: 14px;
                color: #1C1C1E;
            }
            QLabel#title {
                font-size: 18px;
                font-weight: bold;
                color: #007AFF;
            }
            QTextEdit {
                border: 1px solid #D2D2D7;
                border-radius: 8px;
                background-color: white;
                padding: 10px;
                font-size: 14px;
            }
        """)

        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)

        # 邮件标题
        title_label = QLabel(subject)
        title_label.setObjectName("title")
        layout.addWidget(title_label)

        # 发件人和时间
        info_layout = QHBoxLayout()
        info_layout.setSpacing(20)

        sender_label = QLabel(f"发件人: {sender}")
        time_label = QLabel(f"时间: {time}")

        info_layout.addWidget(sender_label)
        info_layout.addWidget(time_label)
        layout.addLayout(info_layout)

        # 邮件内容
        content_edit = QTextEdit()
        content_edit.setReadOnly(True)
        content_edit.setText(content)
        layout.addWidget(content_edit)


class TempMailTool(QMainWindow):
    def __init__(self):
        self.rootshPage = RootshPage()
        self.applymailApi = ApplymailApi()
        self.getmailApi = GetmailApi()
        self.getCode = GetCode()

        # 已存在邮件 id 值列表
        self.existing_list = []

        # 邮箱后缀列表
        self.suffix_list = []

        self.mail, self.suffix_list, self.replace_one, self.replace_two = self.rootshPage.get_rootsh_cookie()

        super().__init__()
        self.setWindowTitle("临时邮箱工具")
        self.icon_img = QIcon(self.get_resource_path('images/favicon.ico'))
        self.setWindowIcon(self.icon_img)

        self.setMinimumSize(600, 500)

        # 设置Win11风格的样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #F5F5F7;
            }
            QLineEdit {
                padding: 8px;
                border: 1px solid #D2D2D7;
                border-radius: 8px;
                font-size: 14px;
                background-color: white;
            }
            QLineEdit:focus {
                border-color: #007AFF;
                outline: none;
            }
            QPushButton {
                background-color: #007AFF;
                color: white;
                border-radius: 8px;
                padding: 8px 16px;
                font-size: 14px;
                border: none;
            }
            QPushButton:hover {
                background-color: #0066CC;
            }
            QPushButton:pressed {
                background-color: #0052A3;
            }
            QLabel {
                font-size: 14px;
                color: #1C1C1E;
            }
            QLabel#countdown {
                font-size: 20px;
                font-weight: bold;
                color: #007AFF;
            }
            QListWidget {
                border: 1px solid #D2D2D7;
                border-radius: 8px;
                background-color: white;
                padding: 8px;
            }
            QListWidget::item:hover {
                background-color: #F0F7FF;
                border-radius: 4px;
            }
            QListWidget::item:selected {
                background-color: #E6F0FF;
                border-radius: 4px;
                color: #007AFF;
            }
            QGroupBox {
                border: 1px solid #D2D2D7;
                border-radius: 8px;
                margin-top: 10px;
                padding: 10px;
                background-color: white;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
                color: #6E6E73;
                font-size: 13px;
            }
            QComboBox {
                padding: 8px;
                border: 1px solid #D2D2D7;
                border-radius: 8px;
                font-size: 14px;
                background-color: white;
                min-width: 100px;
            }
            QComboBox::drop-down {
                subcontrol-origin: padding;
                subcontrol-position: top right;
                width: 20px;
                border-left-width: 1px;
                border-left-color: #D2D2D7;
                border-left-style: solid;
                border-top-right-radius: 8px;
                border-bottom-right-radius: 8px;
                background-color: #007AFF;
            }
            QComboBox::down-arrow {
                image: none;
                color: white;
                width: 0;
                height: 0;
                border-style: solid;
                border-width: 5px 5px 0 5px;
                border-color: white transparent transparent transparent;
                margin-right: 5px;
            }
            QComboBox QAbstractItemView {
                border: 1px solid #D2D2D7;
                selection-background-color: #007AFF;
                background-color: white;
            }
        """)

        # 创建中心部件和布局
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(15)

        # 创建输入区域
        input_group = QGroupBox("邮箱申请")
        input_layout = QHBoxLayout()
        input_layout.setSpacing(10)

        self.email_input = QLineEdit()
        self.email_input.setPlaceholderText("请输入账号（不超过10个字符）")
        self.email_input.setMaxLength(10)
        input_layout.addWidget(self.email_input)

        # 添加邮箱后缀下拉选择框
        self.suffix_combo = QComboBox()
        self.suffix_combo.setEditable(False)  # 允许手动输入新的后缀
        # 您可以在这里添加默认的邮箱后缀
        self.add_combo()
        input_layout.addWidget(self.suffix_combo)

        self.apply_btn = QPushButton("申请邮箱")
        self.apply_btn.clicked.connect(self.start_countdown)
        input_layout.addWidget(self.apply_btn)

        input_group.setLayout(input_layout)
        main_layout.addWidget(input_group)

        # 创建倒计时区域
        countdown_group = QGroupBox("邮箱有效期")
        countdown_layout = QVBoxLayout()
        countdown_layout.setAlignment(Qt.AlignmentFlag.AlignCenter)

        self.countdown_label = QLabel("未申请邮箱")
        self.countdown_label.setObjectName("countdown")
        self.countdown_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        countdown_layout.addWidget(self.countdown_label)

        countdown_group.setLayout(countdown_layout)
        main_layout.addWidget(countdown_group)

        # 创建邮件列表区域
        mail_group = QGroupBox("收到的邮件")
        mail_layout = QVBoxLayout()

        self.mail_list = QListWidget()
        self.mail_list.doubleClicked.connect(self.show_email_detail)  # 双击事件
        mail_layout.addWidget(self.mail_list)

        mail_group.setLayout(mail_layout)
        main_layout.addWidget(mail_group)

        # 初始化倒计时相关变量
        self.countdown_seconds = 600  # 10分钟 = 600秒
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_countdown)

        # 创建邮件获取定时器 (每30秒获取一次新邮件)
        self.email_fetch_timer = QTimer(self)
        self.email_fetch_timer.setInterval(2000)  # 2秒 = 2000毫秒
        self.email_fetch_timer.timeout.connect(self.fetch_emails)

        # 默认添加三条收到的邮件（包含详情内容）
        # self.add_email(
        #     "欢迎使用临时邮箱服务",
        #     "系统通知",
        #     "2025-08-04 09:30",
        #     "尊敬的用户，欢迎使用临时邮箱服务！\n\n"
        #     "您可以使用此邮箱接收各类验证邮件，保护您的个人隐私安全。\n"
        #     "邮箱有效期为10分钟，超时后将自动失效。\n\n"
        #     "感谢您的使用！"
        # )
        # self.add_email(
        #     "您的验证码是123456",
        #     "安全中心",
        #     "2025-08-04 10:15",
        #     "您好，您的验证码是：123456\n\n"
        #     "此验证码用于身份验证，请勿泄露给他人。\n"
        #     "验证码有效期为5分钟，请尽快使用。"
        # )
        # self.add_email(
        #     "新消息通知",
        #     "用户服务",
        #     "2025-08-04 14:22",
        #     "您好，您有一条新的系统通知：\n\n"
        #     "您的临时邮箱服务已使用1次，本月剩余29次免费使用机会。\n"
        #     "如需更多服务，请升级至高级会员。\n\n"
        #     "详情请查看官网帮助中心。"
        # )

    def add_combo(self):
        for s in self.suffix_list:
            # if s == 'mxl001.win':
            self.suffix_combo.addItem(f'@{s}')

    def get_resource_path(self, relative_path):
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

    def add_email(self, subject, sender, time, content):
        """添加收到的邮件到列表（包含详情内容）"""
        # 创建列表项，显示摘要信息
        display_text = f"[{time}] {sender}: {subject}"
        item = QListWidgetItem(display_text)

        # 存储完整邮件数据作为item的data
        item.setData(Qt.ItemDataRole.UserRole, {
            "subject": subject,
            "sender": sender,
            "time": time,
            "content": content
        })

        self.mail_list.addItem(item)
        # 滚动到底部显示最新邮件
        self.mail_list.scrollToBottom()

    # 修改 show_email_detail 方法，添加异常处理
    def show_email_detail(self):
        """显示邮件详情"""
        selected_items = self.mail_list.selectedItems()
        if not selected_items:
            return

        try:
            # 获取选中项的完整邮件数据
            email_data = selected_items[0].data(Qt.ItemDataRole.UserRole)

            mail_id = email_data["content"]
            # 查询邮件详情
            email_full_encoded = self.email_full.replace("@", self.replace_one).replace(".", self.replace_two)

            id = f'{email_full_encoded}/{mail_id}'
            # http://rootsh.com:8003/win/99577))()*mxl001_+=_+win/2dAtAcDjEq89iCasrfVOrh.eml
            mail_content = self.getCode.get_code(self.apply_return_mail, self.apply_return_time, id)

            # 使用 BeautifulSoup 解析 HTML 并提取文本内容
            soup = BeautifulSoup(mail_content, 'html.parser')
            # 提取纯文本内容
            plain_text = soup.get_text()

            # 创建并显示详情对话框
            dialog = EmailDetailDialog(
                email_data["subject"],
                email_data["sender"],
                email_data["time"],
                plain_text,
                self
            )
            dialog.exec()
        except Exception as e:
            print(f"显示邮件详情时出错: {e}")
            # 可以添加一个错误提示对话框
            error_dialog = EmailDetailDialog(
                "错误",
                "系统",
                "",
                f"无法加载邮件内容: {str(e)}",
                self
            )
            error_dialog.exec()

    def start_countdown(self):
        """开始倒计时"""
        if not self.email_input.text().strip():
            self.countdown_label.setText("请输入账号")
            return

        # 重置倒计时时间
        self.countdown_seconds = 600  # 重置为10分钟

        # 如果定时器已经在运行，则重启它
        if self.timer.isActive():
            self.timer.stop()

        self.timer.start(1000)  # 每秒更新一次
        self.update_countdown()

        # 不再禁用按钮和输入框，允许重复点击
        # self.apply_btn.setEnabled(False)
        # self.email_input.setEnabled(False)

        # 这里应该调用用户的邮箱申请接口
        # 使用邮箱前缀和后缀组合申请邮箱
        self.email_full = self.email_input.text() + self.suffix_combo.currentText()
        apply_res = self.applymailApi.get_applymail(self.email_full, self.mail)
        self.apply_return_mail = apply_res.cookies['mail']
        self.apply_return_time = apply_res.cookies['time']
        print(f"apply_return_mail: {self.apply_return_mail}")
        print(f"apply_return_time: {self.apply_return_time}")

        # 重启邮件获取定时器
        if self.email_fetch_timer.isActive():
            self.email_fetch_timer.stop()
        self.email_fetch_timer.start()

        # 立即获取一次邮件
        self.fetch_emails()

    def fetch_emails(self):
        """定时获取新邮件的接口调用方法"""
        # 定时获取邮件
        mail_json_data = self.getmailApi.get_getmail(self.email_full, self.apply_return_mail)
        emails = mail_json_data.get('mail')
        # 返回信息
        # {"to":"9527000@bccto.cc","mail":[["Easy","1505448035@qq.com","测试","2025-08-04 17:09:47","PFpbgZpBD4juBwlt9ZmMj4.eml",2549]],"success":"true","time":1754298593}
        print(f"mail_json_data: {mail_json_data}")

        for email in emails:
            if email[4] in self.existing_list:
                continue
            self.add_email(
                email[2],
                email[1],
                email[3],
                email[4]
            )
            self.existing_list.append(email[4])
        pass

    def update_countdown(self):
        """更新倒计时显示"""
        if self.countdown_seconds <= 0:
            self.timer.终止()
            self.countdown_label.setText("邮箱已过期")
            self.apply_btn.setEnabled(True)
            self.email_input.setEnabled(True)
            return

        minutes = self.countdown_seconds // 60
        seconds = self.countdown_seconds % 60
        self.countdown_label.setText(f"剩余时间: {minutes:02d}:{seconds:02d}")
        self.countdown_seconds -= 1


if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 设置应用程序风格为Fusion以确保跨平台一致性
    app.setStyle("Fusion")

    # 调整颜色以更接近Win11风格
    palette = app.palette()
    palette.setColor(QPalette.ColorRole.Window, QColor(245, 245, 247))
    palette.setColor(QPalette.ColorRole.WindowText, QColor(28, 28, 30))
    palette.setColor(QPalette.ColorRole.Base, QColor(255, 255, 255))
    palette.setColor(QPalette.ColorRole.AlternateBase, QColor(245, 245, 247))
    palette.setColor(QPalette.ColorRole.ToolTipBase, QColor(255, 255, 255))
    palette.setColor(QPalette.ColorRole.ToolTipText, QColor(28, 28, 30))
    palette.setColor(QPalette.ColorRole.Text, QColor(28, 28, 30))
    palette.setColor(QPalette.ColorRole.Button, QColor(245, 245, 247))
    palette.setColor(QPalette.ColorRole.ButtonText, QColor(28, 28, 30))
    palette.setColor(QPalette.ColorRole.BrightText, QColor(255, 255, 255))
    palette.setColor(QPalette.ColorRole.Link, QColor(0, 122, 255))
    palette.setColor(QPalette.ColorRole.Highlight, QColor(0, 122, 255))
    palette.setColor(QPalette.ColorRole.HighlightedText, QColor(255, 255, 255))
    app.setPalette(palette)

    window = TempMailTool()
    window.show()
    sys.exit(app.exec())
